/**
 * @author Kristian Mandrup
 * @date June 10, 2009
 * @version 0.1
 * 
 * m3gen :: JsTreeNodeBuilder
 * 
 * - Create a jsTree node using the NodeObj created by JSONObjParser
 * 
 * By seperating parsing of the jsonObj from the creation of the jsTreeNode
 * This framework enables substitution of the JsTreeNodeBuilder with alternative
 * Node builders in case the underlying data model of jsTree changes 
 * or in case m3gen is used to generate alternative tree models 
 * 
 * Usage 
 * -----
 * var my_jsTreeNodeBuilder = new m3gen.JsTreeNodeBuilder(generatorModel);
 * var my_jsTreeNode = my_jsTreeNodeBuilder.execute(my_instanceModel);
 */

/**
 * JsTreeNodeBuilder constructor
 * Sets up JsTreeNodeBuilder for use
 * @param {Object} createOptions
 *   
 *  TODO: handle options!
 */
m3gen.JsTreeNodeBuilder = function(createOptions) {
	if (arguments.length < 1 || m3gen.util.invalidOptions(createOptions))
		return;		
	this.init(createOptions);
}

// inherit from Builder
m3gen.JsTreeNodeBuilder.inherits(m3gen.Base);

/**
 * 
 * @param {Object} createOptions
 */
m3gen.JsTreeNodeBuilder.prototype.init = function(createOptions){
	this.setClassName('JsTreeNodeBuilder');		
	// call Builder superclass initializer 
	this.uber('init', createOptions);			
}

/**
 * All JsTreeNodeBuilders must have an execute function
 * 
 * @param {Object} nodeObj - The nodeObj to use for creating the jsTreeNode
 */

/**
 * doExecute default empty wrapper
 * @param {Object} options
 */
m3gen.JsTreeNodeBuilder.prototype.execute = function(options){
	return this.doExecute(options);
}

/**
 * 
 * @param {Object} nodeObj
 */
m3gen.JsTreeNodeBuilder.prototype.doExecute = function(nodeObj){	
	if (arguments.length < 1) 
		throw m3gen.exception.MissingNodeObject;
			
	var attributes = this.getAttributesBuilderInstance().execute(nodeObj);
	var state = this.getStateBuilderInstance().execute(nodeObj);
	var data = this.getDataBuilderInstance().execute(nodeObj);
	var metaData = this.getMetaDataBuilderInstance().execute(nodeObj);
	var children = this.getChildrenBuilderInstance().execute(nodeObj);
	
	// must always have an attributes key with at least an id
	var jsTreeNode = {
		attributes: attributes,
	};
	// data	
	if (this.isValidObj(data)) {
		jsTreeNode.data = data;
	}
	
	// metadata
	if (this.isValidObj(metaData)) {
		jsTreeNode.mdata = metaData;
	}
	// children and children show state (open/closed)
	if (this.isNotEmptyArray(children)) {
		// only set state if there is children
		if (this.isString(state) ) {
			jsTreeNode.state = state;
		}
		jsTreeNode.children = children;
	}	
	// only return valid jsTreeNodes!
	if (this.isValidJsTreeNode(jsTreeNode))
		return jsTreeNode;	
	else {
		throw m3gen.exception.InvalidJsTreeNode;
	}
}


